package com.example.spring.demo.controller;

import com.example.spring.demo.common.error.CustomException;
import com.example.spring.demo.service.MinioService;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2024/12/30 9:16
 **/
@RestController
@RequestMapping("/api/minio")
@RequiredArgsConstructor
public class MinioController {
    private final MinioService minioService;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            minioService.ensureBucketExists();
            minioService.uploadFile(file.getOriginalFilename(), file);
            return "File uploaded successfully";
        } catch (Exception e) {
            throw new CustomException("文件上传失败!");
        }
    }

    @GetMapping("/download/{objectName}")
    public byte[] downloadFile(@PathVariable String objectName) {
        try {
            InputStream inputStream = minioService.downloadFile(objectName);
            return inputStream.readAllBytes();
        } catch (Exception e) {
            throw new CustomException("文件下载失败!");
        }
    }

    @GetMapping("/list")
    public List<String> listFiles() {
        try {
            List<Item> items = minioService.listObjects();
            return items.stream()
                    .map(Item::objectName)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            throw new CustomException("文件列表为空!");
        }
    }
}
